package hotnet.test;

import java.io.IOException;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;

import hotnet.buffer.IoBuffer;
import hotnet.config.IoSessionConfig;
import hotnet.filter.IoFilterAdapter;
import hotnet.filter.IoFilterChainBuilder;
import hotnet.handler.IoHandlerAdapter;
import hotnet.nio.NioSocketAcceptor;
import hotnet.service.IoAcceptor;
import hotnet.session.IoSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

class IoHandlerServer extends IoHandlerAdapter {

	@Override
	public void messageReceived(IoSession session, Object message)
			throws Exception {
		IoBuffer buffer = (IoBuffer)message;
		Charset charset = Charset.forName("UTF-8");
		CharsetDecoder decoder = charset.newDecoder();
		CharBuffer charBuffer = decoder.decode(buffer.buf().asReadOnlyBuffer());
		
		String m = new String(charBuffer.toString());
		System.out.println("handler receive:" + m);
	
		
		String hString = "#hello world from server#";
		IoBuffer nBuffer = IoBuffer.wrap(hString.getBytes());
		session.write(nBuffer);
		
		System.out.println("handler write:" + m);
	}
	
}

class MyIoFilter extends IoFilterAdapter {

	public MyIoFilter(String name) {
		super(name);
	}
	
	@Override
	public void messageReceived(NextFilter nextFilter, IoSession session,
			Object message) throws Exception{
		if (message instanceof IoBuffer) {
			IoBuffer buffer = (IoBuffer)message;
			Charset charset = Charset.forName("UTF-8");
			CharsetDecoder decoder = charset.newDecoder();
			CharBuffer charBuffer = null;
			charBuffer = decoder.decode(buffer.buf().asReadOnlyBuffer());
			String m = new String(charBuffer.toString());
		}
		
		nextFilter.messageReceived(session, message);
	}

	@Override
	public void sessionOpened(NextFilter nextFilter, IoSession session) throws Exception {
		nextFilter.sessionOpened(session);
	}
}

public class Server {
	private final static Logger logger = LoggerFactory.getLogger(Server.class);


	public static void main(String[] args) {
		IoAcceptor serverAcceptor = new NioSocketAcceptor();
		IoSessionConfig config = serverAcceptor.getDefaultSessionConfig();
		IoFilterChainBuilder serverChainBuilder = serverAcceptor.getIoFilterChainBuilder();

		serverChainBuilder.addLast(new MyIoFilter("MyIoFilter"));
		serverChainBuilder.addLast(new );

		serverAcceptor.setHandler(new IoHandlerServer());
		try {
			serverAcceptor.bind(9090);
			logger.info("9090 bind success");			
		} catch (IOException e) {
			e.printStackTrace();	
		}
	}
}
